﻿using System;
using System.Collections.Generic;

namespace Ymatou.ServiceCenter
{
    /// <summary>
    /// 服务依赖存储服务
    /// </summary>
    internal static class ServiceDependencyStorage
    {
        private static readonly SynchronizedDictionary<string, ServiceDependencySampling> SamplingDictionary = new SynchronizedDictionary<string, ServiceDependencySampling>();

        static ServiceDependencyStorage()
        {
            DaemonThread.Run(SendSampling, (ex) => { Logger.Error("SendSamplingException", ex); }, RpcClientConfigManager.GetSendServiceDependencyInterval);
        }

        /// <summary>
        /// 发送采样数据
        /// </summary>
        private static void SendSampling()
        {
            IList<ServiceDependencySampling> list = new List<ServiceDependencySampling>();
            SamplingDictionary.Foreach((pair) =>
            {
                ServiceDependencySampling sampling = pair.Value.CloneAndReset();
                list.Add(sampling);
            });

            ServiceCenterFacade.SaveServiceDependencySamplings(list);
            Logger.Debug(string.Format("SendSampling,发送{0}条服务依赖采样数据到服务中心！", list.Count));
        }

        /// <summary>
        /// 保存服务依赖请求信息
        /// </summary>
        /// <param name="serviceDependencyRequest"></param>
        public static void Save(ServiceDependencyRequest serviceDependencyRequest)
        {
            if (serviceDependencyRequest == null)
                return;
            try
            {
                string key = string.Format("{0}_{1}_{2}_{3}", serviceDependencyRequest.ConsumerAppId, serviceDependencyRequest.ProviderAppId
                    , serviceDependencyRequest.ApiName, serviceDependencyRequest.ApiPath);
                if (!SamplingDictionary.ContainsKey(key))
                {
                    ServiceDependencySampling sampling = new ServiceDependencySampling
                    {
                        BeginTime = DateTime.Now,
                        ConsumerAppId = serviceDependencyRequest.ConsumerAppId,
                        ApiName = serviceDependencyRequest.ApiName,
                        ProviderAppId = serviceDependencyRequest.ProviderAppId,
                        ApiPath = serviceDependencyRequest.ApiPath,                        
                        TotalRequestElapsedMilliseconds = serviceDependencyRequest.RequestElapsedMilliseconds,
                        TotalRequestTimes = 1,
                        TotalFailTimes = serviceDependencyRequest.IsFail ? 1 : 0,
                        MaxElapsedTime = serviceDependencyRequest.RequestElapsedMilliseconds,
                        MinElapsedTime = serviceDependencyRequest.RequestElapsedMilliseconds
                    };
                    SamplingDictionary.Add(key, sampling);
                    ServiceCenterFacade.SendFastServiceDependency(sampling);//新增时立刻发送一条记录，已便可以快速的让服务中心建立服务依赖关系图表
                    Logger.Debug(string.Format("{0} 不存在SamplingDictionary，发送到服务端", key));
                }
                else
                {
                    SamplingDictionary[key].ChangeData(serviceDependencyRequest.RequestElapsedMilliseconds, serviceDependencyRequest.IsFail);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("收集服务依赖请求出现异常！", ex);
            }

        }

    
    }
}
